<template>
  <div>
    <el-upload
      v-model:file-list="fileList"
      action="/ypAdmi/upload"
      :headers="headers"
      :limit="1"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :before-upload="beforeAvatarUpload"
      :on-success="successUpload"
      :on-remove="removeUpload"
    >
      <el-icon><Plus /></el-icon>
    </el-upload>

    <el-dialog v-model="dialogVisible">
      <img :src="dialogImageUrl" alt="Preview Image" class="img1" />
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, inject } from "vue";
import { useStore } from "vuex";
import { ElMessage } from "element-plus";
let store = useStore();
let fileList = reactive([]);
let form = inject("form1");
if (store.state.goodsFormType.type == 1) {
  form.pics = reactive([]);
} else {
  let ls = "";
  if (form.pics.length != 0) {
    for (let i = 0; i < form.pics.length; i++) {
      fileList.push({
        url: "/ypAdmi/" + form.pics.mid,
      });
    }
    form.pics = reactive([{ pic: ls }]);
  }
}
const dialogImageUrl = ref("");
let dialogVisible = ref(false);
let headers = reactive({
  Authorization: store.state.token,
});

const successUpload = (response) => {
  ElMessage.success("上传成功");
  form.pics.push({ pic: response.data.tmp_path });
};

const removeUpload = () => {
  form.pics.pop();
  ElMessage.success("删除成功");
};
// 打开diloag  窗口
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url;
  dialogVisible.value = true;
};
//判断文件格式
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== "image/jpeg" && rawFile.type !== "image/png") {
    ElMessage.error("文件必须是JPG 或 PNG 格式!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("文件不能大于 2MB!");
    return false;
  }
  return true;
};
</script>
<style lang="scss" scoped>
.img1 {
  width: 100%;
}
</style>

